'use strict';

const Controller = require('egg').Controller;
class DormController extends Controller {
  // 批量添加宿舍
  async insertManyDorm() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const payload = ctx.request.body;
    const dorms = payload.dorms;
    const res = await ctx.service.dorm.insertManyDorms(dorms);
    if (res.errcode) {
      resMsg.errcode = 1;
      resMsg.errorDorms = res.errorDorms;
      resMsg.msg = "操作失败，请查看！";
    }

    ctx.body = resMsg;
  }

  // 根据宿舍号查找宿舍
  async findDormByNumber() {
    const resMsg = {
      errcode: 0,
      data: {},
      message: "success",
    };

    const { ctx } = this;
    resMsg.data = await ctx.service.dorm.findDormByNumber(ctx.request.query.dorm_num);
    ctx.body = resMsg;
  }

  // 查询宿舍
  async searchDorms() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const conditions = ctx.request.body;
    resMsg.data = await ctx.service.dorm.searchDorms(conditions);
    ctx.body = resMsg;
  }

  // 根据宿舍号查询宿舍人数
  async checkDormStudentCount() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const dorm_num = ctx.request.body.dorm_num;
    const res = await ctx.service.dorm.checkDormStudentCount(dorm_num);
    if (res.errcode) {
      resMsg.errcode = res.errcode;
      resMsg.msg = res.msg;
    }
    resMsg.data = res.data;
    ctx.body = resMsg;
  }

  // 删除一个宿舍
  async removeOneDorm() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const id = ctx.request.body.id;
    const res = await ctx.service.dorm.removeOneDorm(id);
    if (res.errcode) {
      resMsg.errcode = res.errcode;
      resMsg.errors = res.errors;
      resMsg.msg = "删除失败";
    }
    ctx.body = resMsg;
  }

  // 修改宿舍信息
  async updateDorm() {
    const { ctx } = this;
    const resMsg = ctx.helper.resMsg();
    const payload = ctx.request.body;
    const res = await ctx.service.dorm.updateDorm(payload);
    if (res.errcode) {
      resMsg.errcode = res.errcode;
      resMsg.msg = res.msg;
    }
    ctx.body = resMsg;
  }
}

module.exports = DormController;
